package com.zllkj.mm.module.shopping.fragment

import android.util.Log
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.zllkj.mm.R
import com.zllkj.mm.adapter.ShoppingCartListAdapter
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.BaseString
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.base.BaseTitleFragment
import com.zllkj.mm.common.L
import com.zllkj.mm.model.entity.Goods
import com.zllkj.mm.model.entity.ShoppingCartListBean
import com.zllkj.mm.model.entity.ShoppingCartUpdateBean
import com.zllkj.mm.module.shopping.vm.ItemShoppingCartIListVM
import com.zllkj.mm.util.JsonUtil
import com.zllkj.mm.util.common.FormatUtil
import kotlinx.android.synthetic.main.activity_shopping_cart.*
import kotlinx.android.synthetic.main.activity_shopping_cart.view.*
import java.lang.StringBuilder
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.List
import kotlin.collections.forEachIndexed
import kotlin.collections.map
import kotlin.collections.mapIndexed
import kotlin.collections.set
import kotlin.collections.toMutableList

class ShoppingCardFragment : BaseTitleFragment() {

    lateinit var listAdapter : ShoppingCartListAdapter
    var datas = ArrayList<ItemShoppingCartIListVM>()
    var currentPage = 1;

    var isDeleteMode = false



    override fun getContentLayoutId(): Int {
        return R.layout.activity_shopping_cart
    }

    override fun loadData() {
        super.loadData()


        setCommonTitle("购物车")
        setRightBtn("管理", View.OnClickListener {
            if (!isDeleteMode) {
                mRootView.tv_shopping_cart_all_price.visibility = View.INVISIBLE
                mRootView.tv_shopping_cart_all_price_title.visibility = View.INVISIBLE
                mRootView.tv_shopping_cart_pay_button.text = "删除"
                isDeleteMode = true
            } else {
                mRootView.tv_shopping_cart_all_price.visibility = View.VISIBLE
                mRootView.tv_shopping_cart_all_price_title.visibility = View.VISIBLE
                mRootView.tv_shopping_cart_pay_button.text = "结算"
                isDeleteMode = false
            }

            datas?.map { it.shopCheckBoxIsChecked = false }
            listAdapter.notifyDataSetChanged()
            updateShoppingCartTotalPrice()
            cb_shopping_cart_select_all.isChecked = false
        })

        listAdapter = ShoppingCartListAdapter(R.layout.item_shopping_cart_list,datas)
        mRootView.rv_shoppingcart_recycleview.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = listAdapter
        }
        var emptyView = layoutInflater.inflate(R.layout.include_empty_layout,null).apply {
            findViewById<AppCompatTextView>(R.id.tv_empty_title).text = "购物车竟然是空的"
            findViewById<AppCompatTextView>(R.id.tv_empty_content).text = "再忙，也要记得买点什么犒赏自己~"
        }
        listAdapter.emptyView = emptyView

        mRootView.tv_shopping_cart_pay_button.setOnClickListener {
            payOrRemoveGoods()
        }

        mRootView.cb_shopping_cart_select_all.setOnCheckedChangeListener { buttonView, isChecked ->
            selectAll(isChecked)
        }

        loadShoppingCartList()

        listAdapter.onShoppingCartCheckListener = object : ShoppingCartListAdapter.OnShoppingCartCheckListener{

            override fun onAllCheck(isCheck: Boolean) {
                updateShoppingCartTotalPrice()
            }

            override fun onSubGoodsCheck(isCheck: Boolean, subPosition: Int) {
                updateShoppingCartTotalPrice()
            }

            override fun onGoodsCountUpdate(position: Int, subPosition: Int, count: Int) {
                updateGoodsCount(position,subPosition,count)
            }
        }

    }

    private fun updateGoodsCount(position: Int, subPosition: Int, count: Int){
        addSubscribe(RetrofitHelper.getInstance().shoppingCartApi.updateShoppingCartCount((HashMap<String, Any>().apply {
            this["goodsNum"] = count
            this["shoppingCartItemId"] = datas[position].goodsList[subPosition].shoppingCartGoodsId
        })).compose<ShoppingCartUpdateBean>(RxHelper.defaultHandleResult<ShoppingCartUpdateBean>()).subscribe(object : ProgressSubscriber<ShoppingCartUpdateBean>(context){
            override fun onSucc(t: ShoppingCartUpdateBean?) {

                listAdapter.notifyDataSetChanged()
                updateShoppingCartTotalPrice()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

    private fun loadShoppingCartList(){
        addSubscribe(RetrofitHelper.getInstance().shoppingCartApi.getShoppingCartList((HashMap<String, Any>().apply {
            this["pageSize"] = 20
            this["currentPage"] = currentPage
        })).compose<List<ShoppingCartListBean>>(RxHelper.defaultHandleResult<List<ShoppingCartListBean>>()).subscribe(object : ProgressSubscriber<List<ShoppingCartListBean>>(context){
            override fun onSucc(t: List<ShoppingCartListBean>?) {
                t?.let {  list ->

                    list.map {
                        var vm = ItemShoppingCartIListVM()
                        vm.goodsList = it.goodsList.toMutableList()
                        vm.shopName = it.shopName
                        vm.shopId = it.shopId.toString()
                        vm.goodsList.map { vm.goodsCheckedFlag.add(false) }

                        datas.add(vm)
                    }
                }
                listAdapter.notifyDataSetChanged()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

   private fun removeAllShoppingCart(){

       var goodsIds = StringBuilder()
       datas.map {
           it.goodsCheckedFlag.mapIndexed { index, b ->
               if (b) {
                  goodsIds.append(it.goodsList[index].shoppingCartGoodsId.toString() +",")
               }
           }
       }
       goodsIds.deleteCharAt(goodsIds.lastIndex)

        addSubscribe(RetrofitHelper.getInstance().shoppingCartApi.deleteShoppingCartItem((HashMap<String, Any>().apply {
            this["shoppingCartGoodsIds"] = goodsIds.toString()
        })).compose<BaseString>(RxHelper.defaultHandleResult<BaseString>()).subscribe(object : ProgressSubscriber<BaseString>(context){
            override fun onSucc(t:BaseString?) {
                datas.clear()
                loadShoppingCartList()
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

    /**
     * 删除购物车或者提取
     */
    private fun payOrRemoveGoods(){
        if (isDeleteMode) {
            removeAllShoppingCart()
        } else {
            var checkList = ArrayList<ItemShoppingCartIListVM>()

            datas.map {
                if (it.shopCheckBoxIsChecked) { //如果是全选的 直接丢进去
                    checkList.add(it)
                } else { //否则的话就一个一个 找
                    var newGoodsLIst = ArrayList<Goods>()
                    var newVM = ItemShoppingCartIListVM()
                    newVM.shopName = it.shopName
                    newVM.shopId = it.shopId
                    newVM.userId = it.userId
                    it.goodsCheckedFlag.mapIndexed { index, b ->
                        if (b) {
                            newGoodsLIst.add(it.goodsList[index])
                        }
                    }
                    newVM.goodsList = newGoodsLIst
                    if (newGoodsLIst.size > 0) {
                        checkList.add(newVM)

                    } else {

                    }
                }
            }
            if(checkList.size > 0) addFragment(OrderConfirmFragment(checkList)) else L.showToast("请选择商品")

        }
    }


    private fun selectAll(isCheck:Boolean){
        datas.forEachIndexed { index, itemShoppingCartIListVM ->
            itemShoppingCartIListVM.shopCheckBoxIsChecked = isCheck
            itemShoppingCartIListVM.goodsList.mapIndexed{index,it ->
                itemShoppingCartIListVM.goodsCheckedFlag[index] = isCheck
            }
        }
        listAdapter.notifyDataSetChanged()
        updateShoppingCartTotalPrice()
    }

    /**
     * 更新购物车价格
     */
   private fun updateShoppingCartTotalPrice(){
        var total = 0
        datas.map {
            it.goodsCheckedFlag.mapIndexed { index, b ->
                if (b) {
                    total += it.goodsList[index].unitPrice * it.goodsList[index].goodsNum
                }
            }
        }
        mRootView.tv_shopping_cart_all_price.text = FormatUtil.bigDecimalUtilFormat(total.toString(),"100")
    }
}